package org.example.exampreparationtreasure.util;

import jakarta.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class CsvUtils {
	public static void writeCsv(HttpServletResponse response, String filename, List<String> headers, List<List<String>> rows) throws Exception {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/csv;charset=UTF-8");
		String encoded = URLEncoder.encode(filename, StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20");
		response.setHeader("Content-Disposition", "attachment; filename=" + encoded + ".csv");
		try (PrintWriter writer = response.getWriter()) {
			writer.println(String.join(",", headers));
			for (List<String> row : rows) {
				writer.println(String.join(",", row));
			}
			writer.flush();
		}
	}
} 